package com.tea.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tea.Model.Category;
import com.tea.Model.dto.CategoryBatchSortDTO;
import com.tea.Model.dto.CategorySortDTO;
import com.tea.mapper.CategoryMapper;
import com.tea.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class CategoryService extends ServiceImpl<CategoryMapper, Category> {

    /**
     * 获取按排序字段排序的分类列表
     */
    public List<Category> listOrderBySort() {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort_order", "category_id");
        return list(queryWrapper);
    }

    /**
     * 批量更新分类排序
     */
    @Transactional
    public Result<String> batchUpdateSort(CategoryBatchSortDTO batchSortDTO) {
        try {
            List<CategorySortDTO> categories = batchSortDTO.getCategories();

            for (CategorySortDTO categorySort : categories) {
                Category category = new Category();
                category.setCategoryId(categorySort.getCategoryId());
                category.setSortOrder(categorySort.getSortOrder());

                boolean success = updateById(category);
                if (!success) {
                    log.error("更新分类排序失败，分类ID: {}", categorySort.getCategoryId());
                    return Result.error("更新分类排序失败");
                }
            }

            log.info("批量更新分类排序成功，共更新 {} 个分类", categories.size());
            return Result.success("排序更新成功");

        } catch (Exception e) {
            log.error("批量更新分类排序异常", e);
            return Result.error("排序更新失败：" + e.getMessage());
        }
    }

    /**
     * 单个分类排序更新
     */
    public Result<String> updateSort(Long categoryId, Integer sortOrder) {
        try {
            Category category = new Category();
            category.setCategoryId(categoryId);
            category.setSortOrder(sortOrder);

            boolean success = updateById(category);
            if (success) {
                return Result.success("排序更新成功");
            } else {
                return Result.error("排序更新失败");
            }
        } catch (Exception e) {
            log.error("更新分类排序异常，分类ID: {}, 排序值: {}", categoryId, sortOrder, e);
            return Result.error("排序更新失败：" + e.getMessage());
        }
    }
}
